<template>
	<view class="todaybills">
		<view class="headerHeight">
			<view class="header u-flex u-row-around u-p-20">
				<view class="flex-column u-margin-right-30">
					<view>本月工资</view>
					<view>{{ getThisMonthSalary }}元</view>
				</view>
				<view class="flex-column">
					<view>今日工资</view>
					<view>{{ getTodaySalary }}元</view>
				</view>
			</view>
			<view class="u-flex u-p-10 u-p-t-10">
				<button size="mini" type="primary" @click="getBoss">添加老板</button>
				<button size="mini" type="primary" @click="getProduct">添加商品</button>
				<button size="mini" type="primary" @click="getAddBill">添加账单</button>
			</view>
			<view class="title u-text-center u-p-t-10 u-p-b-10 border-y">今日账单列表</view>
		</view>
		<view class="content">
			<scroll-view scroll-y="true" :style="{height:contentHeight + 'px'}">
				<u-collapse :head-style="{backgroundColor:'#f5f5f5',paddingLeft:'20rpx'}" :body-style="{color:'#000'}">
					<d-collapse-item class="border-y" style="margin-top:-1px;" :title="item.name"
						v-for="(item, index) in todayList" :key="index">
						<template v-slot:title>
							<view class="u-flex" style="width:100%;">
								<view class="u-flex-1">{{ item.name }}</view>
								<view class="u-p-r-20">总计：{{ getBossTotal(item.tobills) }}元</view>
							</view>
						</template>

						<view v-if="item.tobills.length > 0"
							class="u-flex u-row-around u-border-top-bottom u-p-t-20 u-p-b-20">
							<view>商品</view>
							<view>单价</view>
							<view>数量</view>
						</view>
						<view class="u-p-20 u-text-center" v-if="item.tobills.length < 1">暂无数据</view>
						<d-swipe-action  v-for="(row,i) in item.tobills" :key="i" :index="i" :show="row.show" btn-width="120" @click="(index,index1)=>handleSelectRow(item.tobills,index,index1)"
							@open="open(item.tobills,i)" :options="options">
							<view class="u-flex u-row-around u-border-top-bottom u-p-t-20 u-p-b-20">
								<view>{{ row.product }}</view>
								<view>{{ row.price }}</view>
								<view>{{ row.count }}</view>
							</view>
						</d-swipe-action>
					</d-collapse-item>
				</u-collapse>
			</scroll-view>
		</view>
		<u-modal v-model="addBillState" :title="(isUpdateBill ? '修改' : '添加') + '账单'" :show-cancel-button="true" @confirm="handleComfirm"
			:async-close="true">
			<view>
				<u-form class="u-p-20" :model="form" ref="uForm">
					<u-form-item label="老板">
						<u-input v-model="form.boss" type="select" border @click="showBossList = true"
							:select-open="showBossList" placeholder="请选择老板" />
						<d-action-sheet :list="bossList" v-model="showBossList" @click="selectBoss"></d-action-sheet>
					</u-form-item>
					<u-form-item label="商品">
						<u-input v-model="form.product" type="select" border @click="handleShowProduct"
							:select-open="showProductList" placeholder="请选择商品" />
						<d-action-sheet :list="productList" v-model="showProductList" @click="selectProduct">
						</d-action-sheet>
					</u-form-item>
					<u-form-item label="单价">
						<u-input disabled v-model="form.price" border placeholder="商品单价" />
					</u-form-item>
					<u-form-item label="数量" :borderBottom="false">
						<u-input v-model="form.count" border placeholder="请输入数量" />
					</u-form-item>
				</u-form>

			</view>
		</u-modal>
	</view>
</template>

<script>
	import dCollapseItem from '../components/d-collapse-item.vue'
	import dActionSheet from '../components/d-action-sheet.vue'
	import dSwipeAction from '../components/d-swipe-action.vue'
	export default {
		components: {
			dCollapseItem,
			dActionSheet,
			dSwipeAction
		},
		data() {
			return {
				pH:0,
				updateOrDeleteId:null,
				isUpdateBill:false,
				showBossList: false,
				showProductList: false,
				bossList: [],
				productList: [],
				form: {},
				addBillState: false,
				contentHeight: 0,
				todayList: [],
				thismonthList: [],
				options: [{
						text: '修改',
						style: {
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
			}
		},
		computed: {
			// 计算每个老板的合计
			getBossTotal: () => list => list.reduce((sum, item) => sum + item.count * parseFloat(item.price), 0),
			// 计算今天工资
			getTodaySalary() {
				let total = 0
				this.todayList.forEach(item => {
					let r = this.getBossTotal(item.tobills)
					total += r
				})
				return total
			},
			// 计算本月工资
			getThisMonthSalary() {
				let total = 0
				this.thismonthList.forEach(item => {
					let r = this.getBossTotal(item.tobills)
					total += r
				})
				return total
			}
		},
		mounted() {
			this.$nextTick(function(){
				this.getContentHeight()
			})
		},
		created() {
			this.getTodayBills()
			this.getThisMonthBills()
		},
		methods: {
			// 报工列表添加show属性判断显示左滑
			open(list, index) {
				this.$set(list[index],'show',true)
				list.map((val, idx) => {
					if (index != idx) this.$set(list[idx],'show',false)
				})
			},
			// 判断点击修改还是删除
			async handleSelectRow(list,index, index1) {
				this.updateOrDeleteId = list[index]._id
				this.form.boss = list[index].boss
				this.form.count = list[index].count
				this.form.price = list[index].price
				this.form.product = list[index].product
				if (index1 == 1) {
					this.handleDeleteBill()
				} else {
					this.isUpdateBill = true
					this.addBillState = true
				}
			},
			// 获取本月账单
			async getThisMonthBills() {
				const res = await this.$u.get('/thismonthbills', this.form)
				this.thismonthList = res.map(item => {
					item.tobills.map(to => {
						this.$set(to, 'show', false)
						return to
					})
					return item
				})
			},
			handleShowProduct() {
				if (this.form.boss) {
					this.showProductList = true
				}
			},
			// 获取今日账单
			async getTodayBills() {
				const res = await this.$u.get('/todaybills')
				this.todayList = res
			},
			// 账单确定 添加 Or 修改
			handleComfirm(){
				if(this.isUpdateBill){
					this.handleUpdateBill()
				}else{
					this.handleAddBill()
				}
			},
			// 删除账单
			async handleDeleteBill(){
				uni.showModal({
				    title: `[${this.form.boss}][${this.form.product}][${this.form.price}][${this.form.count}]`,
				    content: `确定要删除此账单吗？此操作不可恢复！`,
				    success: async (res)=> {
				        if (res.confirm) {
				            await this.$u.delete(`/rest/bills/${this.updateOrDeleteId}`)
				            this.$u.toast('删除成功')
				            this.getTodayBills()
				        }
				    }
				})
				
			},
			// 修改账单
			async handleUpdateBill(){
				await this.$u.put(`/rest/bills/${this.updateOrDeleteId}`,this.form)
				this.addBillState = false
				this.$u.toast('修改成功')
				this.getTodayBills()
			},
			// 添加账单
			async handleAddBill() {
				const res = await this.$u.post('/bills', this.form)
				this.addBillState = false
				this.$u.toast('添加成功')
				this.getTodayBills()
			},
			// 添加账单弹窗
			getAddBill() {
				this.addBillState = true
				this.isUpdateBill = false
				this.form = {}
				this.getBossList()
			},
			// 选择老板
			selectBoss(index) {
				this.$set(this.form, 'boss', this.bossList[index].name)
				this.$set(this.form, 'bossId', this.bossList[index]._id)
				this.getProductList()
			},
			// 选择商品
			selectProduct(index) {
				this.$set(this.form, 'product', this.productList[index].name)
				this.$set(this.form, 'productId', this.productList[index]._id)
				this.$set(this.form, 'price', this.productList[index].price)
			},
			// 获取老板列表
			async getBossList() {
				const res = await this.$u.get('/bosses')
				this.bossList = res.map(item => {
					item.text = item.name
					return item
				})
			},
			// 获取商品列表
			async getProductList() {
				let id = this.bossList.filter(item => item.name === this.form.boss)[0]._id
				const res = await this.$u.get(`/products/${id}`)
				this.productList = res.map(item => {
					item.text = item.name
					return item
				})
			},
			// 跳转 添加老板
			getBoss() {
				this.$u.route({
					url: 'pages/category/boss',
				})
			},
			// 跳转 添加商品
			getProduct() {
				this.$u.route({
					url: 'pages/category/product',
				})
			},
			// 获取scroll-view滚动高度
			getContentHeight() {
				uni.getSystemInfo({
				    success:res =>{
				        let bodyHeight = res.windowHeight
						this.$u.getRect('.headerHeight').then(res => {
							this.contentHeight = bodyHeight - res.height
						})
				    }
				})
			}
		}
	}
</script>

<style>
	.todaybills {
		width: 100%;
		height: 100%;
	}

	.header {
		border-bottom: 1px solid;
	}

	.header>view {
		text-align: center;
		flex: 1;
	}

	.header>view view {
		border: 1px solid;
		padding: 20rpx 30rpx;
		width: 100%;
	}

	.header>view view:last-child {
		margin-top: -1px;
	}
</style>
